﻿
using FullCoreDBModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using MyApp.Common;
using Newtonsoft.Json;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace MyApp.WebApi.Controllers
{
    public class ApiResultFilterAttribute : ActionFilterAttribute
    {

        /// <summary>
        /// 是否往数据库记录api访问明细日志
        /// </summary>
        bool saveRequestInfo = false;
        private Stopwatch stopwatch;

        public ApiResultFilterAttribute()
        {

        }

        /// <summary>
        ///     进入action之前做权限验证
        /// </summary>
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            ResponseApi<object> resultMsg = new ResponseApi<object>();
            if (context.Result is ObjectResult objectResult)
            {
                context.Result = new ObjectResult(new ResponseApi<object> { code = 200, msg = "", data = objectResult.Value });
               
            }
            else if (context.Result is EmptyResult)
            {
                context.Result = new ObjectResult(new ResponseApi<string> { code = 404, msg = "未找到资源" });
            }
            else if (context.Result is ContentResult contentResult)
            {
                context.Result = new ObjectResult(new ResponseApi<object> { code = 200, msg = "", data = contentResult.Content });
            }
            else if (context.Result is StatusCodeResult statusResult)
            {
                context.Result = new ObjectResult(new ResponseApi<string> { code = statusResult.StatusCode, data = "", msg = "" });
            }
        }

        private int ToInt(double dou)
        {
            try
            {
                return Convert.ToInt32(dou);
            }
            catch (Exception)
            {
                return 0;
            }
        }

        /// <summary>
        /// 通过请求地址 获取服务节点 
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string GetNode(string path)
        {
            string Default = string.Empty;

            var arr = path.Substring(1).Split('/');
            if (arr.Length >= 1)
            {
                Default = arr[1];
            }
            return Default;
        }

        private bool IsNumber(string str)
        {
            try
            {
                int i = Convert.ToInt32(str);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        ///通过请求地址 获取路由
        /// </summary>
        /// <returns></returns>
        private string GetRouteForAPI(string path)
        {
            var list = path.Split('/');

            string route = path.Substring(path.IndexOf("api") + "api".Length);
            if (IsNumber(list.ToList().Last()))
            {
                route = route.Substring(0, route.Length - list.ToList().Last().Length - 1);
            }

            return route;
        }

        /// <summary>
        ///     统一响应格式
        /// </summary>
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            //stopwatch.Stop();
            //if (filterContext.ActionContext.Response != null)
            //{
            //    if (saveRequestInfo)
            //    {
            //        Task.Run(() =>
            //               {
            //                   try
            //                   {
            //                       RequestInfo request = new RequestInfo
            //                       {
            //                           IP = filterContext.ActionContext.Request.GetClientIpAddress(),
            //                           Milliseconds = ToInt(stopwatch.ElapsedMilliseconds),
            //                           StatusCode = (int)filterContext.ActionContext.Response.StatusCode,
            //                           Method = filterContext.ActionContext.Request.Method.ToString(),
            //                           Url = filterContext.Request.RequestUri.LocalPath.ToString(),
            //                           CreateTime = DateTime.Now
            //                       };
            //                       request.Node = GetNode(request.Url);
            //                       request.Route = GetRouteForAPI(request.Url);
            //                       RequestInfoRepository.SaveInDataBase(request);
            //                   }
            //                   catch (Exception ex)
            //                   {
            //                       log.Error(ex);
            //                   }
            //               });

            //    }
            //    var result = new ResponseApi<object>();
            //    // 取得由 API 返回的状态代码
            //    result.code = (int)filterContext.ActionContext.Response.StatusCode;
            //    // 取得由 API 返回的资料
            //    result.data = filterContext.ActionContext.Response.Content.ReadAsAsync<object>().Result;
            //    // 取得由 API 返回的消息
            //    result.msg = filterContext.ActionContext.Response.IsSuccessStatusCode ? null : filterContext.ActionContext.Response.ReasonPhrase;
            //    // 设置自定义Table序列化
            //    JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
            //    // 获取自定义Attribute
            //    if (Attribute.IsDefined(((ReflectedHttpActionDescriptor)((System.Web.Http.ApiController)filterContext.ActionContext.ControllerContext.Controller).ActionContext.ActionDescriptor).MethodInfo, typeof(TableConvert)))
            //    {
            //        serializerSettings.Converters.Add(new CustomTableConverter());
            //        serializerSettings.Formatting = Formatting.Indented;
            //        serializerSettings.NullValueHandling = NullValueHandling.Include;
            //    }
            //    var jsResult = JsonConvert.SerializeObject(result, serializerSettings);
            //    //log.Info("请求结果：" + jsResult);
            //    var response = new HttpResponseMessage
            //    {
            //        Content = new StringContent(jsResult,
            //            Encoding.GetEncoding("UTF-8"), "application/json")
            //    };

            //    //结果转为自定义消息格式
            //    var httpResponseMessage = response;

            //    // 重新封装回传格式
            //    filterContext.Response = httpResponseMessage;
            //}
        }

    }
}